package com.cqjtu.eecs.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.cqjtu.eecs.entity.NaturalClass;
import com.cqjtu.eecs.entity.Role;
import com.cqjtu.eecs.entity.Teacher;
import com.cqjtu.eecs.entity.dto.*;
import com.cqjtu.eecs.entity.vo.NaturalClassVo;
import com.cqjtu.eecs.entity.vo.NaturalClassVo2;
import com.cqjtu.eecs.entity.vo.StudentVO;
import com.cqjtu.eecs.entity.vo.StudentVO2;
import com.cqjtu.eecs.service.IMajorService;
import com.cqjtu.eecs.service.INaturalClassService;
import com.cqjtu.eecs.service.ITeacherService;
import com.cqjtu.eecs.service.IUserService;
import com.cqjtu.eecs.utils.MapUtils;
import com.cqjtu.eecs.utils.Result;
import com.cqjtu.eecs.utils.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 自然班 前端控制器
 * </p>
 *
 * @author    
 * @since 2022-03-07
 */
@RestController
@RequestMapping("/natural-class")
@Api(tags = "自然班管理")
public class NaturalClassController {
    @Autowired
    private INaturalClassService iNaturalClassService;
    @Autowired
    private IMajorService iMajorService;
    @Autowired
    private MapUtils mapMajorUtil;
    @Autowired
    private ITeacherService iTeacherService;
    @Autowired
    private IUserService iUserService;

    @ApiOperation("分页查询所有自然班级")
    @GetMapping("/selectAllNaturalClass/{currPage}/{pageSize}")
    public Result selectAllNaturalClass( @PathVariable("currPage") Integer currPage,@PathVariable("pageSize") Integer pageSize){
        int currPage_old=currPage;
        currPage=(currPage-1)*pageSize;
        Map<String,String> mapMajor= mapMajorUtil.getMapMajorUtil();
        Map<Integer, TeacherDto2> teacherUtil = mapMajorUtil.getTeacherUtil();
        List<NaturalClass> naturalClasses = iNaturalClassService.selectAllNaturalClassLimit(currPage , pageSize);
        List<NaturalClassVo> result=new ArrayList<>();
        for (int i=0;i<naturalClasses.size();i++){
            TeacherDto2 t=teacherUtil.get(naturalClasses.get(i).getTid());
            String teacherCode=null;
            String teacherName=null;
            if(t!=null){
                teacherCode=t.getTeacherCode();
                teacherName=t.getTeacherName();
            }
            result.add(new NaturalClassVo(naturalClasses.get(i).getMajorCode(),mapMajor.get(naturalClasses.get(i).getMajorCode()),
                                            naturalClasses.get(i).getGrade(),naturalClasses.get(i).getNaturalClassName(),
                    teacherCode,
                    teacherName));
        }
        NaturalClassVo2 naturalClassVo2=new NaturalClassVo2(iNaturalClassService.count(),currPage_old,pageSize,result);
        return Result.success(naturalClassVo2);
    }
    @ApiOperation("分页根据年级查询某一年的所有班级")
    @GetMapping("/selectAllNaturalClassByGrade/{grade}/{currPage}/{pageSize}")
    public Result selectAllNaturalClassByGrade(@PathVariable("grade") Integer grade, @PathVariable("currPage") Integer currPage,@PathVariable("pageSize") Integer pageSize){
        int currPage_old=currPage;
        currPage=(currPage-1)*pageSize;
        Map<String,String> mapMajor= mapMajorUtil.getMapMajorUtil();
        Map<Integer, TeacherDto2> teacherUtil = mapMajorUtil.getTeacherUtil();
        List<NaturalClass> naturalClasses = iNaturalClassService.selectAllNaturalClassByGrade(grade,currPage,pageSize);
        List<NaturalClassVo> result=new ArrayList<>();
        for (int i=0;i<naturalClasses.size();i++){
            TeacherDto2 t=teacherUtil.get(naturalClasses.get(i).getTid());
            String teacherCode=null;
            String teacherName=null;
            if(t!=null){
                teacherCode=t.getTeacherCode();
                teacherName=t.getTeacherName();
            }
            result.add(new NaturalClassVo(naturalClasses.get(i).getMajorCode(),
                    mapMajor.get(naturalClasses.get(i).getMajorCode()),
                    naturalClasses.get(i).getGrade(),naturalClasses.get(i).getNaturalClassName(),
                   teacherCode,
                    teacherName));
        }

        NaturalClassVo2 naturalClassVo2=new NaturalClassVo2(iNaturalClassService.count(),currPage_old,pageSize,result);
        return Result.success(naturalClassVo2);
    }
    @ApiOperation("分页根据年级和专业代码，查询下面所有班级")
    @GetMapping("/selectAllNaturalClassByGradeAndMajorCode/{grade}/{majorCode}/{currPage}/{pageSize}")
    public Result selectAllNaturalClassByGradeAndMajorName(@PathVariable("grade") Integer grade,@PathVariable("majorCode") String majorCode,
                                                           @PathVariable("currPage") Integer currPage,@PathVariable("pageSize") Integer pageSize){
        int currPage_old=currPage;
        currPage=(currPage-1)*pageSize;
        Map<String,String> mapMajor = this.mapMajorUtil.getMapMajorUtil();
        Map<Integer, TeacherDto2> teacherUtil = mapMajorUtil.getTeacherUtil();
        List<NaturalClass> naturalClasses = iNaturalClassService.selectAllNaturalClassByGradeAndmajorName(grade, majorCode, currPage, pageSize);
        List<NaturalClassVo> result=new ArrayList<>();
        for (int i=0;i<naturalClasses.size();i++){
            TeacherDto2 t=teacherUtil.get(naturalClasses.get(i).getTid());
            String teacherCode=null;
            String teacherName=null;
            if(t!=null){
                teacherCode=t.getTeacherCode();
                teacherName=t.getTeacherName();
            }
            result.add(new NaturalClassVo(naturalClasses.get(i).getMajorCode(),mapMajor.get(naturalClasses.get(i).getMajorCode()),
                    naturalClasses.get(i).getGrade(),naturalClasses.get(i).getNaturalClassName(),
                    teacherCode,
                    teacherName));
        }
        NaturalClassVo2 naturalClassVo2=new NaturalClassVo2(iNaturalClassService.count(),currPage_old,pageSize,result);
        return Result.success(naturalClassVo2);

    }
    @ApiOperation(value = "增加一个自然班", notes = "专业代码和专业名称可以任写一个，如果全写，优先选专业代码")
    @PostMapping("/addNaturalClass")
    public Result addNaturalClass(@RequestBody NaturalClassDTO naturalClassDTO){
        Map mapMajor = this.mapMajorUtil.getMapMajorUtil();
        if(naturalClassDTO.getMajorCode()!=null||!naturalClassDTO.getMajorCode().equals("")){
            NaturalClass naturalClass=new NaturalClass(naturalClassDTO.getMajorCode(),1,naturalClassDTO.getGrade(),naturalClassDTO.getNaturalClassName());
            if(mapMajor.get(naturalClass.getMajorCode())==null) return Result.error(-1,"专业不存在，创建失败");
            List<NaturalClass> list = iNaturalClassService.list();
            for (int i=0;i<list.size();i++){
                if(list.get(i).equals(naturalClass)) return Result.error(-1,"该班级已存在");
            }
            boolean save = iNaturalClassService.save(naturalClass);
            if(save) return Result.success();
        }else {
            Set<String> set = mapMajor.keySet();
            for (String t:set){
                //有这个专业
                if(mapMajor.get(t).equals(naturalClassDTO.getMajorName())){
                    List<NaturalClass> list = iNaturalClassService.list();
                    NaturalClass naturalClass=new NaturalClass(t,1,naturalClassDTO.getGrade(),naturalClassDTO.getNaturalClassName());
                    for (int i=0;i<list.size();i++){
                        if(list.get(i).equals(naturalClass)) return Result.error(-1,"该班级已存在");
                    }
                    return Result.success();
                }
            }
        }
        return Result.error();
    }
    @DeleteMapping("/deleteNaturalClass")
    @ApiOperation("删除一个自然班级")
    public Result deleteNaturalClass(@RequestBody NaturalClassDTO2 naturalClassDTO2){
        List<NaturalClass> list = iNaturalClassService.list();
        NaturalClass temp=new NaturalClass(naturalClassDTO2.getMajorCode(),0,naturalClassDTO2.getGrade(),naturalClassDTO2.getNaturalClassName());
        for (int i=0;i<list.size();i++){
            if(temp.equals(list.get(i))) {
                boolean b = iNaturalClassService.removeById(list.get(i).getNcId());
                if(b) return Result.success();
            }
        }
        return Result.error(-1,"没有这个班级");
    }

    @PutMapping("/putNaturalClass")
    @ApiOperation("修改一个自然班级")
    public Result putNaturalClass(@RequestBody NaturalClassDTO3 naturalClassDTO3){
        List<NaturalClass> list = iNaturalClassService.list();
        NaturalClass temp=new NaturalClass(naturalClassDTO3.getMajorCode_old(),0,naturalClassDTO3.getGrade_old(),naturalClassDTO3.getNaturalClassName_old());
        for (int i=0;i<list.size();i++){
            if(temp.equals(list.get(i))) {
                int i1 = iNaturalClassService.getBaseMapper().updateById(new NaturalClass(naturalClassDTO3.getMajorCode_now(),list.get(i).getNcId(),naturalClassDTO3.getGrade_now(),naturalClassDTO3.getNaturalClassName_now()));
                if(i1==1) return Result.success();
            }
        }
        return Result.error(-1,"没有该班级");
    }
    @PostMapping("/naturalClassIsHave")
    @ApiOperation("查询是否存在这个班级")
    public Result naturalClassIsHave(@RequestBody NaturalClassDTO2 naturalClassDTO2){
        List<NaturalClass> list = iNaturalClassService.list();
        NaturalClass temp=new NaturalClass(naturalClassDTO2.getMajorCode(),0,naturalClassDTO2.getGrade(),naturalClassDTO2.getNaturalClassName());
        for (int i=0;i<list.size();i++){
            if(temp.equals(list.get(i))) {
                return Result.success(ResultCode.SUCCESS,"该班级存在");
            }
        }
        return Result.error(-1,"没有这个班级");
    }
    @GetMapping("/selectAllClassByMajorCode/{majorCode}/{currPage}/{pageSize}")
    @ApiOperation("根据专业代码查询所有班级")
    public  Result selectAllClassByStuCode(@PathVariable String majorCode,@PathVariable Integer currPage,@PathVariable Integer pageSize){
        Map<Integer, String> majorUtilNaturalClassUtil = mapMajorUtil.getNaturalClassUtil();
        Map<Integer, TeacherDto2> teacherUtil = mapMajorUtil.getTeacherUtil();
        Map<String, String> mapMajorUtil = this.mapMajorUtil.getMapMajorUtil();
        Map<String,Object> param=new HashMap<>();
        param.put("major_code",majorCode);
        List<NaturalClass> list =iNaturalClassService.getBaseMapper().selectByMap(param);
        //List<NaturalClass> list = iNaturalClassService.list();
        List<NaturalClassVo> collect=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            Integer tid = list.get(i).getTid();
            TeacherDto2 teacherDto2 = teacherUtil.get(tid);
            String teacherCode=null;
            String teacherName=null;
            if(teacherDto2!=null){
                teacherCode=teacherDto2.getTeacherCode();
                teacherName=teacherDto2.getTeacherName();
            }
            collect.add(new NaturalClassVo(list.get(i).getMajorCode(),mapMajorUtil.get(list.get(i).getMajorCode()),
                                            list.get(i).getGrade(),list.get(i).getNaturalClassName(),teacherCode,teacherName));
        }

        //从第几条数据开始
        int firstIndex = (currPage - 1) * pageSize;
        //到第几条数据结束
        int lastIndex = currPage * pageSize;

        try {
            return Result.success(new NaturalClassVo2(collect.size(),currPage,pageSize,collect.subList(firstIndex,lastIndex)));
        }catch (Exception e){
            if(pageSize>collect.size()){
                return Result.success(new NaturalClassVo2(collect.size(),currPage,pageSize,collect.subList(0,collect.size())));
            }
            if(currPage*pageSize>collect.size()&&pageSize>collect.size()){
                return Result.success(new NaturalClassVo2(collect.size(),currPage,pageSize,collect.subList(firstIndex,collect.size())));
            }
            return Result.success(new NaturalClassVo2(collect.size(),currPage,pageSize,null));
        }

    }
    @PutMapping("/addAcademicAdviserByClass")
    @ApiOperation(value = "给自然班分配或者修改学业导师",notes = "参数为教师工号")
    public Result addAcademicAdviserByClass(@RequestBody NaturalClassDTO4 naturalClassDTO4){
        NaturalClass naturalClass=new NaturalClass(naturalClassDTO4.getMajorCode(),null,naturalClassDTO4.getGrade(),naturalClassDTO4.getNaturalClassName());
        NaturalClass naturalClass1 = iNaturalClassService.list().stream().filter(s -> s.equals(naturalClass)).collect(Collectors.toList()).get(0);
        String teacherCode = naturalClassDTO4.getTeacherCode();
        Teacher teacher=iTeacherService.selectTeacherByTeacherCode(teacherCode);
        naturalClass1.setTid(teacher.getTid());
        //将老师插入到自然班
        int op = iNaturalClassService.getBaseMapper().updateById(naturalClass1);
        //添加学业导师角色
        List<Role> roles = iUserService.listRoleByUid(teacher.getUid());
        for (Role role:roles){
            if(role.getRoleName().equals("mentor")){
                return Result.error(-1,"该用户已经是学业导师！");
            }
        }
        boolean b = iUserService.addRoleToUser(teacher.getUid(), "mentor");
        if(op==1&&b) return Result.success("操作成功");
        return Result.error();
    }

    @GetMapping("/selectClassById/{nc_id}")
    @ApiOperation(value = "根据自然班编号返回班级")
    public Result selectClassById(@PathVariable("nc_id") Integer id){
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("nc_id",id);
        NaturalClass naturalClass = iNaturalClassService.getBaseMapper().selectOne(queryWrapper);
        //转化为VO

        NaturalClassVo naturalClassVo=new NaturalClassVo(naturalClass.getMajorCode(),
                                                         mapMajorUtil.getMapMajorUtil().get(naturalClass.getMajorCode()),
                                                         naturalClass.getGrade(),
                                                         naturalClass.getNaturalClassName(),
                                                         mapMajorUtil.getTeacherUtil().get(naturalClass.getTid()).getTeacherCode(),
                                                         mapMajorUtil.getTeacherUtil().get(naturalClass.getTid()).getTeacherName()
                                                            );
        return Result.success(naturalClassVo);
    }

}
